# Copyright 2014 Sean Burford <vk2ete@vk2ete.net>.  All Rights Reserved.
import datetime
import logging
import os

from google.appengine.api import mail
import jinja2
import webapp2

import feed
import ical_ds


JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/html'),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)


class ICalRefreshPage(webapp2.RequestHandler):

  def get(self):
    template_args = {}
    template_args['title'] = 'Feed Refresh'
    template_args['feeds'] = feed.Feed.GetFeedInfos()

    feed_debug = (self.request.params.get('debug') == 'feed')
    feeds = []
    for feed_name in template_args['feeds']:
      feeds.append(feed.Feed(feed_name, feed_debug))
      template_args['feeds'][feed_name].infos = []

    dates = []
    if self.request.params.get('year') and self.request.params.get('month'):
      dates.append((int(self.request.params['year']),
                    int(self.request.params['month'])))
    else:
      now = datetime.datetime.now()
      for days_from_now in (0, 32, 64):
        current_time = now + datetime.timedelta(days_from_now)
        dates.append((current_time.year, current_time.month))

    now = datetime.datetime.now()
    date_range = (now - datetime.timedelta(32),
                  now + datetime.timedelta(94))

    report = []
    for feed_config in feeds:
      existing_events = feed_config.FetchEvents(date_range, {})
      for year, month in dates:
        desc = None
        try:
          events = feed_config.UpdateEvents(year, month, existing_events)
          if events:
            desc = '%04d %02d %d new events' % (year, month, len(events))
        except (feed.Error, ValueError) as e:
          desc = '%04d %02d %s' % (year, month, e)

        if desc:
          template_args['feeds'][feed_name].errors.append(desc)
          report.append('feed %s %s' % (feed_name, desc))

    if report:
      msg = 'Calendar events updated:\n%s' % ('\n'.join(report))
      mail.send_mail(sender='vk2ete@vk2ete.net', to='vk2ete@vk2ete.net',
                     subject='Calendar events added', body=msg)

    template = JINJA_ENVIRONMENT.get_template('feeds.html')
    self.response.write(template.render(template_args))


class ICalPopulateLocationsPage(webapp2.RequestHandler):
  def get(self):
    locations = (
        ical_ds.LocationClue(feed_name='wia', callsign='VK2',
                             keyword='DURAL',
                             location='ARNSW, Quarry Road, Dural, '
                             'New South Wales, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK2',
                             keyword='WYONG',
                             location='Wyong Race Club, Howarth St, Wyong, '
                             'New South Wales, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK3',
                             keyword='CRANBOURNE',
                             location='corner Clarendon and High st, '
                             'Cranbourne, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK3',
                             keyword='HIGHETT',
                             location='33 Turner Rd, Highett, Victoria, '
                             'Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK4',
                             keyword='REDCLIFFE',
                             location='MacFarlane Park in Klingner Rd, '
                             'Kippa Ring, Qld, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK4',
                             keyword='KIPPA RING',
                             location='MacFarlane Park in Klingner Rd, '
                             'Kippa Ring, Qld, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK5',
                             keyword='ST JOHNS AMBULANCE',
                             location='9 Acorn Rd, Camden Park SA, Australia'),
        ical_ds.LocationClue(feed_name='wia', callsign='VK6',
                             keyword='SANDERSON',
                             location='5 Sanderson Rd, Lesmurdie, '
                             'Western Australia, Australia'),
    )
    ical_ds.Put(locations)


class ICalAdminPage(webapp2.RequestHandler):

  def get(self):
    template_args = {}

    template_args['title'] = 'Feed Maintenance'
    template_args['feeds'] = feed.Feed.GetFeedInfos()

    template = JINJA_ENVIRONMENT.get_template('feeds.html')
    self.response.write(template.render(template_args))


application = webapp2.WSGIApplication([
    ('/cal/admin/refresh', ICalRefreshPage),
    ('/cal/admin/locations', ICalPopulateLocationsPage),
    ('/.*', ICalAdminPage),
], debug=False)

